//
//  FileMessage.swift
//  swifttest1
//
//  Created by kologe on 2024/9/30.
//

import Foundation

//1代表文件最后一部分，0代表文件没有传输完毕
let FILEFINAL = UINT32(1)
let FILELEFT = UINT32(0)

let NORMALFILESIZE = 1024*60

import Combine
import Network
class FileMessage:BaseData{
    var fileId:FileId = 0
    var hostName:String
    var fileName:String
    var totalSize:FSIZE
    var state:UINT32 = 0 //listener发送给客户端的，state == 1 代表同意接受文件, 2代表拒绝
    
    override init() {
        hostName = NetMessage.shared().hostName
        fileName = "default"
        state = FILELEFT
        totalSize = 0
        super.init()
    }
    
    enum CodingKeys: String, CodingKey{
        case totalSize
       case hostName
       case fileName
        case state
        case fileId
    }
    
    required init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy:CodingKeys.self)
        totalSize = try container.decode(FSIZE.self, forKey: .totalSize)
        hostName = try container.decode(String.self, forKey: .hostName)
        fileName = try container.decode(String.self, forKey: .fileName)
        state = try container.decode(UINT32.self, forKey: .state)
        fileId = try container.decode(FileId.self, forKey: .fileId)
       
        try super.init(from: decoder)
    }
    
    override func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(totalSize, forKey: .totalSize)
        try container.encode(hostName, forKey: .hostName)
        try container.encode(fileName, forKey: .fileName)
        try container.encode(state, forKey: .state)
        try container.encode(fileId, forKey: .fileId)
        
        try super.encode(to: encoder)
    }
    
    static func packageData(fm:FileMessage,isReq:Bool)  -> Data?{
        let jsonData =  FileMessage.enCodeToJson(obj: fm)
        
        //生成包头
        let ph = PackageHead()
        if(isReq){
            ph.type = FILE_MESSAGE_REQ
        }else{
            ph.type = FILE_MESSAGE_ANS
        }
        ph.msgnum = 1;
        ph.dataCount = PackageHead.headCount+UINT32((Int)(jsonData?.count ?? 0))
        var phData = ph.encode()
        
        phData.append(jsonData!)
        return phData
    }
    
    
    override func textContent()->String{
        return "客户端: "+hostName+" -> "+fileName
    }
    
    static func sendFile(remoteHost:String,fileHandle:FileHandle,fileURL:URL){
        TCPClientManager.shared.sendFileMsg(ip: remoteHost, filePath: fileURL.path)
        //NetAction.sendFileMessage(remoteHost: remoteHost, filePath: fileURL.path())
    }
    
    override func getType() -> UINT32 {
        if(state > 1){
            return FILE_MESSAGE_ANS
        }
        return FILE_MESSAGE_REQ;
    }
    
}
